package cn.flying.cloud.task.core.quartz.listener;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.task.service.TaskJobLogService;

/**
 * @author: admin
 * @date: 2024年01月15日 16:25
 * @version: 1.0
 */
@Component
public class QuartzJobListener implements JobListener {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TaskJobLogService jobLogService;

    /**
     * 监听器名称
     */
    @Override
    public String getName() {
        return "quartz-job-listener";
    }

    /**
     * Scheduler在JobDetail将要被执行时调用这个方法
     *
     * @param context
     * @see #jobExecutionVetoed(JobExecutionContext)
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        logger.info("开始调度任务!任务名称：{}，所属分组：{}", jobKey.getName(), jobKey.getGroup());
        context.getMergedJobDataMap().put("startTime", LocalDateTime.now());
    }

    /**
     * Scheduler在JobDetail即将被执行，但又被TriggerListener否决时会调用该方法
     *
     * @param context
     * @see #jobToBeExecuted(JobExecutionContext)
     */
    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        logger.info("job调度完成，但是被Trigger拒绝!任务名称：{}，所属分组：{}", jobKey.getName(), jobKey.getGroup());
    }

    /**
     * Scheduler在JobDetail被执行之后调用这个方法
     *
     * @param context
     * @param jobException
     */
    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        String instanceId = context.getFireInstanceId();
        logger.info("job执行完成!任务名称：{}，所属分组：{}，执行实例：{}", jobKey.getName(), jobKey.getGroup(), instanceId);

//        Trigger trigger = context.getTrigger();
//        TriggerKey triggerKey = trigger.getKey();
//        LocalDateTime fireTime = context.getFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
//        Class jobClass = jobDetail.getJobClass();
//        JobDataMap dataMap = context.getMergedJobDataMap();
//        LocalDateTime startTime = (LocalDateTime) dataMap.get("startTime");
//        dataMap.remove("startTime");
//
//        LocalDateTime end = LocalDateTime.now();
//        Duration duration = Duration.between(fireTime, end);
//
//        TaskJobLog log = new TaskJobLog();
//        log.setJobName(jobKey.getName());
//        log.setJobGroup(jobKey.getGroup());
////        log.setJobTarget(jobClass.getName());
//        log.setJobParam(Ft.JSON.serializer(dataMap.get(TaskConstant.JOB_PARAM)));
//        log.setJobDesc(jobDetail.getDescription());
//        log.setInstanceId(instanceId);
////        log.setStatus("S");
//        log.setDuration(duration.getSeconds());
//        log.setStartTime(startTime);
//        log.setFireTime(fireTime);
//        log.setEndTime(end);
//        log.setJobMsg("执行成功");
//        if (jobException != null) {
////            log.setStatus("F");
//            log.setJobMsg("执行失败");
//            log.setJobTrace(ExceptionUtils.getStackTrace(jobException));
//        }
//
//        if (logger.isDebugEnabled()) {
//            logger.debug("保存执行日志：{}", Ft.JSON.serializer(log));
//        }
//        try {
//            // 同步执行日志
//            jobLogService.createObj(log);
//        } catch (Exception e) {
//            logger.error("同步执行日志失败", e);
//        }
    }
}
